package com.zyk;

import com.zyk.plugin.DispatcherTransformer;
import com.zyk.plugin.PluginManager;
import com.zyk.utils.StringUtils;
import net.bytebuddy.agent.ByteBuddyAgent;

import java.io.File;

public final class Environment {
    private static final Environment INSTANCE = new Environment();

    private String appName;
    private String nativePrefix;
    private boolean mode;
    private String pid;
    private File pluginFolder;
    private File logFolder;

    private PluginManager pluginManager;
    private DispatcherTransformer dispatcherTransformer;

    private Environment() {}

    public static Environment getInstance() {
        return INSTANCE;
    }

    public String getAppName() {
        return appName;
    }

    public String getNativePrefix() {
        return nativePrefix;
    }

    public boolean isAttachMode() {
        return mode;
    }

    public boolean isJavaagentMode() {
        return !mode;
    }

    public String getModeDesc() {
        return mode ? "attach" : "agent";
    }
    public File getPluginFolder() {
        return pluginFolder;
    }

    public PluginManager getPluginManager() {
        return pluginManager;
    }

    public DispatcherTransformer getDispatcherTransformer() {
        return dispatcherTransformer;
    }

    @Override
    public String toString() {
        return "Environment: {" +
                ", \n\tappName = " + appName +
                ", \n\tpid = " + pid +
                ", \n\tmode = " + getModeDesc() +
                ", \n\tnativePrefix = " + nativePrefix +
                ", \n\tpluginFolder = " + pluginFolder.getPath() +
                ", \n\tlogFolder = " + logFolder.getPath() +
                "\n}";
    }

    void init(String appname, boolean mode) {
        boolean noAppName = StringUtils.isEmpty(appname);
        this.appName = noAppName ? "ja" : appname.toLowerCase();
        String currentDirectory = System.getProperty("user.dir");
        this.pluginFolder = new File(currentDirectory + "/plugins");
        this.logFolder = new File(currentDirectory + "/logs");

        this.nativePrefix = StringUtils.randomMethodName(15) + "_";
        this.mode = mode;
        this.pluginManager = new PluginManager();
        this.dispatcherTransformer = new DispatcherTransformer();
        this.pid = ByteBuddyAgent.ProcessProvider.ForCurrentVm.INSTANCE.resolve();
    }
}
